<template>
  <el-dropdown class="xhykDropdown" v-bind="$attrs"
               :split-button="props.splitButton" :type="typeD"
               @command="handleClick">
    <template #default>
      <slot v-if="!props.splitButton">
        <xhyk-button v-bind="$attrs" :type="typeD">
          <span class="label">{{ props.label }}</span>
          <xhyk-icon class="afterIcon" v-if="props.afterIcon" :type="props.afterIcon"/>
        </xhyk-button>
      </slot>
      <span v-else>
        <span class="label">{{ props.label }}</span>
      </span>
    </template>

    <template #dropdown>
      <el-dropdown-menu>
        <slot name="dropdown">
          <el-dropdown-item v-for="(item, index) in dropdownItem"
                            :key="index" v-bind="item">
            <slot :name="item.slot" :item="item">{{ item.label }}</slot>
          </el-dropdown-item>
        </slot>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import {watch, ref, computed} from 'vue'
import xhykIcon from './xhykIcon.vue'
import xhykButton from './xhykButton.vue'
import {ElDropdown, ElDropdownMenu, ElDropdownItem} from 'element-plus'

defineOptions({name: "xhykDropdown"})
const props = defineProps({
  label: {
    type: String,
    default: '下拉菜单'
  },
  list: {
    type: Object,
    default: []
  },

  afterIcon: {
    type: String,
    default: undefined
  },

  splitButton: {
    type: Boolean,
    default: false
  },

  type: {
    type: [String, Number],
    default: ''
  },

  // 在xhykButtonGroup中调用时，otherQuery为当前下拉菜单配置
  otherQuery: {
    type: Object,
    default: undefined
  },
})


// region 按钮样式
const typeD = computed(() => {
  let temp = props.type.toLowerCase()
  if (temp == '' || temp.includes('f')) {
    return 'default'
  }
  if (temp.includes('p')) {
    return 'primary'
  }
  if (temp.includes('s')) {
    return 'success'
  }
  if (temp.includes('i') && !temp.includes('w')) {
    return 'info'
  }
  if (temp.includes('w')) {
    return 'warning'
  }
  if (temp.includes('d') && !temp.includes('f')) {
    return 'danger'
  }
})
// endregion

const dropdownItem = ref([])
watch(() => props.list, (newV, oldV) => {
  dropdownItem.value = (newV || []).map((item, index) => {
    item.command = item.command || `$${index}_${Date.now()}`
    return item
  })
}, {immediate: true, deep: true})

const handleClick = (which) => {
  const thisItem = dropdownItem.value.find(row => row.command == which)
  if (thisItem) {
    thisItem.click?.(thisItem, props.otherQuery || {
      label: props.label,
      list: props.list,
      type: props.type,
      splitButton: props.splitButton,
      afterIcon: props.afterIcon,
      isMenu: true,
    })
  }
}

</script>

<style scoped lang='scss'>
.label {
  //margin-right: 5px;
}

.afterIcon {
  transform: translateX(4px);
}
</style>